<?php

namespace app\admin\controller\classes;

use addons\exam\enum\PaperMode;
use app\admin\model\exam\ChildCateModel;
use app\admin\model\exam\QuestionModel;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 题库管理
 *
 * @icon fa fa-circle-o
 */
class Tiku extends Backend
{

    /**
     * Tiku模型对象
     * @var \app\admin\model\classes\Tiku
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\classes\Tiku;
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

     /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        $type = $this->request->get('type')??1;
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        if ($type == 2) {
            $this->model = new ChildCateModel();
            $list = $this->model
            ->where($where)
            ->with(['adminName'])
            ->order('id', 'asc')
            ->paginate($limit);
        } else {
            $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        }

        $return = [];
        foreach($list->items() as $v) {
            if (isset($v['admin_name'])) {
                $v['school_name'] = $v['admin_name']['nickname'];
            } else {
                $v['school_name'] = '平台';
            }
            $return[] = $v;
        }
        
        $result = ['total' => $list->total(), 'rows' => $return];
        return json($result);
    }

    /**
     * Selectpage搜索
     *
     * @internal
     */
    public function selectpage()
    {
        return parent::selectpage();
    }

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                //$this->model>valid($params);
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);

                    // 保存试卷固定题目
                    //$this->saveFixQuestion($row, $params, 'edit');
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if (!empty($row['questions'])){
            $questions=json_decode($row['questions'],true);
            $question_id_arr=array_column($questions,'id');

            $row['questions'] = QuestionModel::getFixListByTkIN($question_id_arr, ['cates']);
        }
        $this->view->assign("row", $row);
        //$this->view->assign("configs", json_decode($row['configs'], true));
        return $this->view->fetch();
    }

    //关联员工
    public function ass_staff($ids = null)
    {
        if ($this->request->isAjax()) {
            $stiku_id = $this->request->get('tiku_id');
            $list = $this->model->find($stiku_id);

            $arr = [];
            if(!empty($list->uid))
            {
                $arr = explode(',',$list->uid);
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $search = $this->request->request('search');

            $db2 = Db::connect('db2');
            $where = [];
//            $where['id'] = ['neq',1];
            $where['b.group_id'] = ['=',2];
            if(!empty($search))
            {
                $where['a.nickname'] = ['like','%'.$search.'%'];
            }
            $list = $db2->table('fa_admin a')
                ->join('fa_auth_group_access b','b.uid=a.id')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $rows = $list->items();
            foreach ($rows as $k => $row)
            {
                $rows[$k]['province'] = Db::name('area')->where('id',$row['province'])->value('name');
                $rows[$k]['city'] = Db::name('area')->where('id',$row['city'])->value('name');
                $rows[$k]['district'] = Db::name('area')->where('id',$row['district'])->value('name');
                $rows[$k]['status'] = 0;
                if(in_array($row['id'],$arr))
                {
                    $rows[$k]['status'] = 1;
                }
            }

            $result = array("total" => $list->total(), "rows" => $rows);

            return json($result);
        }
//        dump($ids);
        $this->view->assign('tiku_id',$ids);
        return $this->view->fetch();
    }
    //绑定
    public function bd_staff($ids = null)
    {
        $tiku_id = $this->request->get('tiku_id');
//        dump($ids);die;
        $db2 = Db::connect('db2');
        $row = Db::name('classes_tiku')->find($tiku_id);
        $list = $db2->name('admin')->find($ids);
        if(empty($row['uid']))
        {
            $uid = $ids;
        }
        else
        {
            $uid = $row['uid'] . ',' . $ids;
        }
        if(empty($list['tiku_id']))
        {
            $tiku_ids = $tiku_id;
        }
        else
        {
            $tiku_ids = $list['tiku_id'] . ',' . $tiku_id;
        }

        Db::name('classes_tiku')->where('id',$tiku_id)->update(['uid'=>$uid]);
        $db2->name('admin')->where('id',$ids)->update(['tiku_id'=>$tiku_ids]);
//        $this->success('成功','classes/tiku/ass_staff?ids='.$tiku_id);
        $this->success();
    }
    //解绑
    public function jb_staff($ids = null)
    {
        $tiku_id = $this->request->get('tiku_id');
        $db2 = Db::connect('db2');
        $row = Db::name('classes_tiku')->find($tiku_id);
        $list = $db2->name('admin')->find($ids);
        if(!empty($row['uid']))
        {

            $fa_ids_arr = explode(',',$row['uid']);

            foreach ($fa_ids_arr as $k =>$v)
            {
                if($ids == $v)
                {
                    unset($fa_ids_arr[$k]);
                }
            }
            $fa_ids = implode(',',$fa_ids_arr);
            if(empty($fa_ids))
            {
                $fa_ids = null;
            }
            Db::name('classes_tiku')->where('id',$tiku_id)->update(['uid'=>$fa_ids]);
        }
        if(!empty($list['tiku_id']))
        {
            $synids_arr = explode(',',$list['tiku_id']);
            foreach ($synids_arr as $kk =>$vv)
            {
                if($tiku_id == $vv)
                {
                    unset($synids_arr[$kk]);
                }
            }
            $synids = implode(',',$synids_arr);
            if(empty($synids))
            {
                $synids = null;
            }
            $db2->name('admin')->where('id',$ids)->update(['tiku_id'=>$synids]);
        }

//        $this->success('成功','classes/tiku/ass_staff?ids='.$tiku_id);
        $this->success();
    }
}
